package www.com.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import www.com.utils.JwtUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

public class Interceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handle) throws ServletException {
        try {
            String token = request.getHeader("Authorization").replace("Bearer ", "");
            Boolean diffJwt = JwtUtil.validateJwt(token);
            if(!diffJwt){
                // 验证失败，抛出401错误
                throw new ServletException("Unauthorized");
            }
            return  true;
        } catch (NullPointerException e) {
            // 处理异常
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

//    private boolean isExcludedPath(String path) {
//        // 在此处定义不需要验证的路径，比如登录接口的路径
//        // 判断当前路径是否在排除列表中，如果是则返回true，表示不需要验证；否则返回false，需要进行验证
//        List<String> excludes = Arrays.asList("/login");
//        return  excludes.contains(path);
//    }
}
